package org.jeecg.modules.travel.message;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import com.alibaba.fastjson.JSONObject;



import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
@ServerEndpoint("/travel/message/{userId}")
public class TravelMessage {
    
    private Session session;

    private static CopyOnWriteArraySet<TravelMessage> webSockets =new CopyOnWriteArraySet<>();
    private static Map<String,Session> sessionPool = new HashMap<String,Session>();
    
    @OnOpen
    public void onOpen(Session session, @PathParam(value="userId")String userId) {
        try {
			this.session = session;
			webSockets.add(this);
			sessionPool.put(userId, session);
		} catch (Exception e) {
		}
    }
    
    @OnClose
    public void onClose() {
        try {
			webSockets.remove(this);
		} catch (Exception e) {
		}
    }
    
    @OnMessage
    public void onMessage(String message, @PathParam(value="userId")String userId) {
        try {
            JSONObject msg = JSONObject.parseObject(message);

            
            switch (msg.getString("type")) {
                case "msg":
                    
                    Session tsession = sessionPool.get(msg.getString("tid"));

                    if (tsession != null&&tsession.isOpen()) {
                        try {
                            JSONObject mi = new JSONObject();
                            mi.put("type", "msg");
                            mi.put("tid", userId );
                            mi.put("msg", msg.getString("msg"));
                            tsession.getBasicRemote().sendText(mi.toString());

                            session.getAsyncRemote().sendText("{\"type\":\"msg_status\",\"code\":1}");
                        } catch (Exception e) {
                            session.getAsyncRemote().sendText("{\"type\":\"msg_status\",\"code\":0}");
                        }
                    }



                    break;
            
                default:
                    break;
            }

        } catch (Exception e) {
            session.getAsyncRemote().sendText("{\"type\":\"msg_ret\",\"code\":1,\"msg\":\"系统错误\"}");
        }


    }
  
}
